import React, {memo, useEffect, useRef, useState} from "react";
import {AutoComplete, Dropdown, Menu, message} from "antd";

import Title from "../../../../components/Title/Title";
import {MENU_STYLE} from "../config";
import {deepClone, generateUUID, getAnalysisInfo, getRandomColor} from "../../../../common/utils";
import {useDebounce} from "../../../../common/myHooks";
import {useDispatch, useSelector} from "react-redux";
import {saveTargetName} from "../store/actionCreators";
import {saveTargetSelectedArr} from "../../analysis/components/quantification/store/actionCreators";

export default memo(function PlateTargets(props) {
  const {wells, setWells, targetLibraryStorage, setTargetLibrary, setShowTargetsLibrary, target, setTarget, channels, setTargetNameArr, targetNameArr} = props;
  const targetColorInput = useRef();  //  target颜色选择器
  const [targetIndex, setTargetIndex] = useState(0);  //  选择的target的索引
  const [targetChannelMenu] = useState(() => channels.map(channel => channel.lists.filter(item => item.isSelected)).flat().map(item => item.name)); //  target channel菜单(setting中选中的所有channel)
  const targetQuencher = ["NFQ-MGB", "TAMRA", "None"]; //  target Quencher
  const dispatch = useDispatch();
  const {channelPosition,isCN,data} = useSelector(state => ({
    channelPosition: state.channelReducer.channelPosition,
    isCN: state.languageReducer.isCN,
    data: state.dataReducer.data
  }));
  let cloneWells = [];
  let cloneTarget = [];
  let cloneTargetLibrary = [];
  let cloneTargetNameArr = [];

  //  选择target后的操作
  function selectTargetOperation(indey) {
    cloneTarget = deepClone(target, cloneTarget);
    cloneWells = deepClone(wells, cloneWells);
    if (!cloneTarget[indey].name || !cloneTarget[indey].channel) {  //  没有设置name和channel
      return message.warn("Please enter target name or channel.");
    }
    if (cloneTarget.some((item, index, arr) => index !== indey && item.name === arr[indey].name)) {
      cloneTarget[indey].name = "";
      setTarget(cloneTarget);
      return message.warn("Rename the target name.");
    }
    if (!cloneTarget[indey].opt && cloneWells.some(
      it => it.selected && it.targets.some(item => item.channel === cloneTarget[indey].channel)
    )) {
      return message.warn("Repeat channel.");
    }
    cloneTarget.forEach(target => target.channelIndex = channelPosition.findIndex(item => item.includes(target.channel)));
    if (cloneTarget[indey].opt) { //  取消选中well的target
      cloneTarget[indey].opt = false;
      cloneWells.forEach(well => well.selected && well.targets.some((target, targetIndex, targetsArr) => target.name === cloneTarget[indey].name && targetsArr.splice(targetIndex, 1)));
    } else {  //  增加选中well的target
      if (cloneWells.some(item => item.selected && item.targets.length === 6)) {  //  well中已经有6个target时提示不能超过6个
        return message.warn("Target cannot exceed 6.");
      }
      if (cloneWells.some(item => item.selected
        && item.targets.some(item => item.channelIndex === cloneTarget[indey].channelIndex))) {  //  well中的channel同属于一个channel数组
        return message.warn("Please choose another channel.");
      }
      cloneTarget[indey].opt = true;
      cloneWells.forEach(well => well.selected && well.targets.push({...cloneTarget[indey]}));
    }
    setTarget(cloneTarget);
    setWells(cloneWells);
  }

  //  增加一个Target
  function addTarget() {
    cloneTarget = deepClone(target, cloneTarget);
    cloneTarget.unshift({
      uuid: generateUUID(),
      opt: false,
      show: true,
      name: "",
      color: getRandomColor(),
      channel: "",
      channelIndex: 0,
      quencher: "None",
      reference: false,
      k: -1.0,
      b: -1.0,
      e: -1.0,
      r2: -1.0,
      threshold: 0.01,
      meltThreshold: -1.0,
      cutOff: {
        left: 300,
        right: 700
      },
      comments: ""
    });
    setTarget(cloneTarget);
  }

  //  删除一个Target
  function removeTarget(indey) {
    cloneWells = deepClone(wells, cloneWells);
    cloneTarget = deepClone(target, cloneTarget);
    cloneWells.forEach(well => well.targets.some((target, i, arr) => target.uuid === cloneTarget[indey].uuid && arr.splice(i, 1)));
    cloneTarget.splice(indey, 1);
    dispatch(saveTargetName(cloneTarget.map(item => item.name)));
    setWells(cloneWells);
    setTarget(cloneTarget);
    setTargetNameArr(cloneTarget.map(item => item.name).filter(item => item));
  }

  //  改变Target
  function changeTarget(value, indey, type) {
    cloneTarget = deepClone(target, cloneTarget);
    cloneTarget[indey][type] = value;
    type === "channel" && cloneTarget.forEach(target => target.channelIndex = channelPosition.findIndex(item => item.includes(target.channel)));
    setTarget(cloneTarget);
  }

  //  显示Target颜色板
  function showTargetsColorSetting(indey) {
    setTargetIndex(indey);
    targetColorInput.current.click();
  }

  //  改变Target颜色
  const changeTargetColor = useDebounce(value => {
    cloneTarget = deepClone(target, cloneTarget);
    cloneTarget[targetIndex].color = value;
    setTarget(cloneTarget);
  }, 500);

  //  改变Target Name
  function changeTargetName(value) {
    cloneTarget = deepClone(target, cloneTarget);
    cloneWells = deepClone(wells, cloneWells);
    if (cloneWells.some(well => well.targets.some(target => target.uuid === cloneTarget[targetIndex].uuid))) {
      return message.warn("Please don't change the target name which in the wells.");    //  禁止修改well中存在的targets
    }
    cloneTarget[targetIndex].name = value;
    setTarget(cloneTarget);
  }

  //  选中Target Name
  function selectTargetName(value, option) {
    cloneTarget = deepClone(target, cloneTarget);
    cloneTarget[targetIndex].name = value;
    cloneTarget[targetIndex].color = option.color;
    cloneTarget[targetIndex].channel = option.channel;
    cloneTarget[targetIndex].quencher = option.quencher;
    cloneTarget[targetIndex].channelIndex = channelPosition.findIndex(item => item.includes(cloneTarget[targetIndex].channel));
    cloneTargetNameArr = deepClone(targetNameArr, cloneTargetNameArr);
    cloneTarget.forEach(item => item.name && cloneTargetNameArr.push(item.name));
    setTargetNameArr([...new Set(cloneTargetNameArr)]);
    dispatch(saveTargetName([...new Set(cloneTargetNameArr)]));
    setTarget(cloneTarget);
  }

  function targetLibraryShowAction() {
    setShowTargetsLibrary(true);
    // cloneTargetLibrary = [];
    // target.forEach(item => item.name && cloneTargetLibrary.push({
    //   name: item.name,
    //   color: item.color,
    //   channel: item.channel,
    //   quencher: item.quencher,
    //   writable: false,
    //   selected: false
    // }));
    // setTargetLibrary(cloneTargetLibrary);
  }

  //  获取Target name数组
  function getTargetsNameArr() {
    cloneTargetNameArr = deepClone(targetNameArr, cloneTargetNameArr);
    cloneWells = deepClone(wells, cloneWells);
    target.forEach(item => item.name && cloneTargetNameArr.push(item.name));
    setTargetNameArr([...new Set(cloneTargetNameArr)]);
  }

  return (
    <div className="platePageTarget platePageOperation">
      <Title imgClass="platePageTargetTitleImg" name={isCN ? "目标基因" : "Targets"} btn={isCN ? "添加" : "Add"} btnAction={addTarget} imgAction={targetLibraryShowAction}/>
      <ul>
        <li>{isCN ? "选择" : "Opt"}</li>
        <li>{isCN ? "名称" : "Name"}</li>
        <li>{isCN ? "颜色" : "Color"}</li>
        <li>{isCN ? "通道" : "Channel"}</li>
        <li>{isCN ? "淬灭基团" : "Quencher"}</li>
        <li>{isCN ? "备注" : "Comments"}</li>
        <li>{isCN ? "删除" : "Del"}</li>
      </ul>
      <section className="scrollBarStyle">
        <input ref={targetColorInput} type="color" style={{display: "none"}}
               onChange={e => changeTargetColor(e.target.value)}
        />
        {
          target.map((item, index) => (
            <ul key={index}>
              <li className={item.opt ? "selectedStyle" : ""} onClick={() => selectTargetOperation(index)}/>
              <AutoComplete
                value={item.name}
                style={{width: 130, float: "left", margin: "0 3px"}}
                dropdownClassName="targetNameDropDownStyle"
                options={targetLibraryStorage}
                filterOption={(inputValue, option) =>
                  option.value.toUpperCase().includes(inputValue.toUpperCase())
                }
                onFocus={() => setTargetIndex(index)}
                onSelect={selectTargetName}
                onChange={changeTargetName}
                onBlur={getTargetsNameArr}
              />
              <li>
                <div style={{backgroundColor: `${item.color}`}} onClick={() => showTargetsColorSetting(index)}/>
              </li>
              <Dropdown
                overlay={
                  <Menu>
                    {
                      targetChannelMenu.map(channel => (
                        <Menu.Item key={channel}>
                          <div style={MENU_STYLE} onClick={() => changeTarget(channel, index, "channel")}>{channel}</div>
                        </Menu.Item>
                      ))
                    }
                  </Menu>
                }
                overlayClassName="antdDropDownStyle"
                placement="bottomCenter"
                trigger={['click']}
              >
                <li>{item.channel}</li>
              </Dropdown>
              <Dropdown
                overlay={
                  <Menu>
                    {
                      targetQuencher.map(quencher => (
                        <Menu.Item key={quencher}>
                          <div style={MENU_STYLE} onClick={() => changeTarget(quencher, index, "quencher")}>{quencher}</div>
                        </Menu.Item>
                      ))
                    }
                  </Menu>
                }
                overlayClassName="antdDropDownStyle"
                placement="bottomCenter"
                trigger={['click']}
              >
                <li>{item.quencher}</li>
              </Dropdown>
              <input type="text" value={item.comments} onChange={e => changeTarget(e.target.value, index, "comments")}/>
              <li onClick={() => removeTarget(index)}/>
            </ul>
          ))
        }
      </section>
    </div>
  );
});
